#include "../include/gps_utils.h"
#include "../include/media_defs.h"
#include <pthread.h>

// 声明来自 data_bus.c 的线程和变量
extern pthread_t media_thread, gps_thread, sensor_thread;
extern volatile int run_b, run_gps, run_sensor;
extern void* function_b_thread(void* arg);
extern void* function_gps_thread(void* arg);
extern void* function_sensor_thread(void* arg);

int main() {
    // 初始化线程（后台运行但不打印）
    pthread_create(&media_thread, NULL, function_b_thread, NULL);
    pthread_create(&gps_thread, NULL, function_gps_thread, NULL);
    pthread_create(&sensor_thread, NULL, function_sensor_thread, NULL);
    run_b = 1; // 启动多媒体后台播放
    run_gps = 1; // 启动GPS后台运行
    run_sensor = 1; // 启动传感器后台运行
    int flag = 1;
    while (1) {
        if(flag == 1){
        printf("==================车载信息娱乐系统=================\n");
        printf("1. 多媒体播放控制\n");
        printf("2. GPS导航\n");
        printf("3. 车辆传感器监测\n");
        printf("4. 退出系统\n");
        printf("请选择功能（1-4）：");
        flag = 0;
        }
        int choice;
        if(kbhit()) {
        char c = getchar();
        choice = c - '0';
        
        switch (choice) {
            case 1:
                run_b = 1; // 确保线程运行
                MultimediaControl_Main(); // 前台控制多媒体
                break;
            case 2:
                run_gps = 1; // 确保线程运行
                GPSNavigator_Foreground(); // 前台控制GPS
                break;
            case 3:
                run_sensor = 1; // 确保线程运行
                VehicleSensor_Foreground(); // 前台控制传感器
                break;
            case 4:
                printf("退出系统，感谢使用！\n");
                run_b = 0; // 停止多媒体线程
                run_gps = 0; // 停止GPS线程
                run_sensor = 0; // 停止传感器线程
                pthread_join(media_thread, NULL);
                pthread_join(gps_thread, NULL);
                pthread_join(sensor_thread, NULL);
                return 0;
            default:
                printf("无效选择，请重新输入。\n");
        }
        flag = 1;
    }
    }
    return 0;
}